from flask import Blueprint
from flask import request, current_app
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from shared import db, bcrypt
from http_status import HttpStatus
import utils
from models import ChatRecord, ChatRecordContent

chats_bp = Blueprint('chats', __name__)

@chats_bp.route('add', methods=['POST'])
@jwt_required()
def add_chat_record():
    """添加对话记录"""
    user_id =  get_jwt_identity()
    data = request.get_json()
    role_id = data.get('role_id')
    title = data.get('title')
    if not title:
        return utils.response(False, message='对话标题不能为空')
    # 查询是否存在 like '新会话%' 查询结果总数
    newchatCount = ChatRecord.query.filter(ChatRecord.title.like('新会话%')).filter_by(user_id=user_id, role_id=role_id).count()
    # 新会话标题拼接
    title = gen_chat_title(f'新会话{newchatCount+1}', user_id, role_id, newchatCount)

    chat_record = ChatRecord(user_id=user_id, role_id=role_id, title=title)
    db.session.add(chat_record)
    db.session.commit()
    return utils.response(True, { "id": chat_record.id, "title": title }, '添加成功', HttpStatus.CODE_SUECCESS)

def gen_chat_title(title, user_id, role_id, newchatCount):
    """生成新会话标题"""
    # 查询新标题是否存在
    if ChatRecord.query.filter_by(title=title, user_id=user_id, role_id=role_id).first():
        newchatCount = newchatCount+1
        title = f'新会话{newchatCount}'
        return gen_chat_title(title, user_id, role_id, newchatCount)
    else:
        return title
@chats_bp.route('delete', methods=['POST'])
@jwt_required()
def delete_chat_record():
    """删除对话记录"""
    data = request.get_json()
    chat_record_id = data.get('chat_record_id')
    chat_record = ChatRecord.query.filter_by(id=chat_record_id).first()
    if not chat_record:
        return utils.response(False, message='对话记录不存在')

    chat_record.deleted_at = utils.time_now()
    db.session.commit()
    return utils.response(True, None, '删除成功', HttpStatus.CODE_SUECCESS)

@chats_bp.route('deleteAll', methods=['POST'])
@jwt_required()
def delete_all_chat_record():
    """删除所有对话记录"""
    user_id =  get_jwt_identity()
    data = request.get_json()
    role_id = data.get('role_id')
    chat_records = ChatRecord.query.filter_by(user_id=user_id, role_id=role_id).all()
    # 软删除
    for chat_record in chat_records:
        # db.session.delete(chat_record)
        chat_record.deleted_at = utils.time_now()
    db.session.commit()
    return utils.response(True, None, '删除成功', HttpStatus.CODE_SUECCESS)

@chats_bp.route('list', methods=['GET'])
@jwt_required()
def get_chat_record_list():
    """获取对话记录列表"""
    user_id =  get_jwt_identity()
    # 获取get参数
    role_id = request.args.get('role_id')
    chat_records = ChatRecord.query.filter_by(user_id=user_id, role_id=role_id, deleted_at=None).all()
    data = [chat_record.to_dict() for chat_record in chat_records]
    return utils.response(True, data=data, message='获取成功', status=HttpStatus.CODE_SUECCESS)

@chats_bp.route('updateTitle', methods=['POST'])
@jwt_required()
def update_chat_record_title():
    """更新对话记录标题"""
    data = request.get_json()
    chat_record_id = data.get('chat_record_id')
    title = data.get('title')
    chat_record = ChatRecord.query.filter_by(id=chat_record_id).first()
    if not chat_record:
        return utils.response(False, message='对话记录不存在')
    
    chat_record.title = title
    db.session.commit()
    return utils.response(True, None, '更新成功', HttpStatus.CODE_SUECCESS)


@chats_bp.route('content/list', methods=['GET'])
@jwt_required()
def get_chat_record_content_list():
    """获取对话记录内容列表"""
    chat_record_id = request.args.get('chat_record_id')
    chat_record = ChatRecord.query.filter_by(id=chat_record_id).first()
    if not chat_record:
        return utils.response(False, message='对话记录不存在')
    
    chat_record_contents = ChatRecordContent.query.filter_by(chat_record_id=chat_record_id).order_by(ChatRecordContent.created_at.asc()).all()
    data = [chat_record_content.to_dict() for chat_record_content in chat_record_contents]
    return utils.response(True, data=data, message='获取成功', status=HttpStatus.CODE_SUECCESS)

@chats_bp.route('content/add', methods=['POST'])
@jwt_required()
def add_chat_record_content():
    """添加对话记录内容"""
    data = request.get_json()
    chat_record_id = data.get('chat_record_id')
    msg_id = data.get('msg_id')
    content = data.get('content')
    sender_type = data.get('sender_type')
    chat_record = ChatRecord.query.filter_by(id=chat_record_id).first()
    if not chat_record:
        return utils.response(False, message='对话记录不存在')
    
    chat_record_content = ChatRecordContent(chat_record_id=chat_record_id, msg_id=msg_id, content=content, sender_type=sender_type)
    db.session.add(chat_record_content)
    db.session.commit()
    return utils.response(True, None, '添加成功', HttpStatus.CODE_SUECCESS)

